#!/usr/bin/env python3

import gt
import random
import os

def show_bg():
    print("\033[1;1H", end='', flush=True)

    for r in range(H):
        for c in range(W):
            ch = '#' if r == 0 or c == 0 or r == H - 1 or c == W - 1 else ' '
            print(ch, end='', flush=True)
        print(flush=True)

def ball_init():
    print("\033[2J\033[?25l", end='', flush=True)
    gt.init()
    gt.run(move)


def ball_exit():
    print("\033[?25h\033[%d;1H" % (H + 2), flush=True)
    gt.exit()
    os._exit()


def move():
    global x, y

    while True:
        show_bg()

        print("\033[%d;%dH\033[%dm@\033[0m" % (y, x, color), end='', flush=True)

        if x == 1 or y == 1 or x == W - 1 or y == H - 1:
            ball_exit()

        if direct == 0:
            x += 1
        elif direct == 1:
            x -= 1
        elif direct == 2:
            y -= 1
        elif direct == 3:
            y += 1

        gt.sleep(0.1)


H = 15
W = 80
color = 31
y = 3
x = 3
direct = 0

print("%d, %d" % (gt.w(), gt.h()))
print(gt.size())
input()

ball_init()

while True:
    ch = gt.get()
    if ch == 'q':
        break
    elif ch == 'w':
        direct = 2
    elif ch == 's':
        direct = 3
    elif ch == 'a':
        direct = 1
    elif ch == 'd':
        direct = 0
    elif ch == ' ':
        color = random.randint(30, 37)

ball_exit()

